<?php

class ScheduleController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/columnMgt';
	public $sidebarMenu=array(
								array('label'=>'Roster Control', 'url'=>array('/roster/index')),
								array('label'=>'Shift Changes', 'url'=>array('/shiftChange/management')),
								array('label'=>'User Schedules', 'url'=>array('/schedule/index')),
								array('label'=>'Maintenance', 'url'=>array('/site/maintenance')),
								array('label'=>'Reporting', 'url'=>array('/site/reporting')),
							);
	
	protected function beforeAction($action) {
		if(!(Yii::app()->user->isGuest)) {
			$this->links =  Links::getTeamLinks(Yii::app()->user->team_id);
			
			if(empty($this->links)) {
				$this->links = array(array('label'=>'---','url'=>'#'));
				return true;
			} else
				return true;
		}
		else
			return true;
	}				
	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow', // allow admin user to perform the following actions
				'actions'=>array('index','admin','delete','create','update','view','reporting','FTEReporting'),
				'users'=>array('@'),
				'expression'=>'$user->can_create_edit_shifts == 1',
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate($id)
	{
		$model=new Schedule;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
		$model->iduser = $id;
		$model->team_id = User::model()->findByPk($id)->team;

		if(isset($_POST['Schedule']))
		{
			$model->attributes=$_POST['Schedule'];
			
			//look for a schedule for this user with that weekday
			// to see if it exists through next IF
			$weekdayResult = Schedule::model()->findByAttributes(array('iduser'=>$model->iduser, 'idweekday'=>$model->idweekday));
			
			if ($weekdayResult!=null) {
				$model->addError('idweekday','Error: This user already has a schedule assigned for that weekday!');
				$this->render('create',array('model'=>$model));	
				exit;
			}
			
			if($model->save())
				$this->redirect(array('view','id'=>$model->idschedule));
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}
	
	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
		
		if(isset($_POST['Schedule']))
		{
			$model->attributes=$_POST['Schedule'];

			// tester echo "shift= " .$model->idshift . "qshift= " . $model->idqshift; exit;
		
			
			if($model->save())
				$this->redirect(array('view','id'=>$model->idschedule));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$scheduleModel = $this->loadModel($id);
		$iduser = $scheduleModel->iduser;
		$scheduleModel->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin','id'=>$iduser));
			//$this->redirect(array('admin','id'=>$iduser));
	}

	/**
	 * Render entry point.
	 */
	public function actionIndex()
	{
        $this->render('userSchedule');		
	}	

	/**
	 * Manages all models.
	 */
	public function actionAdmin($id=null)
	{
		//print_r($_POST);exit;
		$model=new Schedule('search');
		$model->unsetAttributes();  // clear any default values
		
		if(isset($_POST['id'])) {
			$model->iduser = $_POST['id'];
			//echo ",post id=".$_POST['id']; 
		} else {
			$model->iduser = $id;
		}
		
		//if($model->iduser == null){echo " its null.. stop";exit;}
		
		if(isset($_GET['Schedule']))
			$model->attributes=$_GET['Schedule'];
	
		$this->render('admin',array('id'=>$model->iduser,
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return Schedule the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=Schedule::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param Schedule $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='schedule-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
	
	 
	public function actionReporting()
	{
	
		$this->sidebarMenu=array(
								array('label'=>'Roster Control', 'url'=>array('/roster/index')),
								array('label'=>'Shift Changes', 'url'=>array('/shiftChange/management')),
								array('label'=>'User Schedules', 'url'=>array('/schedule/index')),
								array('label'=>'Maintenance', 'url'=>array('/site/maintenance')),
								array('label'=>'Reporting', 'url'=>array('/site/reporting')),
							);
							
		$model=new Schedule('search');
		$model->unsetAttributes();  // clear any default values
		
		$model->iduser = Yii::app()->user->iduser;
		$model->team_id = Yii::app()->user->team_id;
		
		if(isset($_GET['Schedule']))
			$model->attributes=$_GET['Schedule'];

		$this->render('reporting',array(
			'model'=>$model,
		));
	}	
	
	public function actionFTEReporting($week=null,$year=null)
	{
	
		$this->sidebarMenu=array(
								array('label'=>'Roster Control', 'url'=>array('/roster/index')),
								array('label'=>'Shift Changes', 'url'=>array('/shiftChange/management')),
								array('label'=>'User Schedules', 'url'=>array('/schedule/index')),
								array('label'=>'Maintenance', 'url'=>array('/site/maintenance')),
								array('label'=>'Reporting', 'url'=>array('/site/reporting')),
							);	
							
		///<<<<<<----------------DEFINE RELEVANT DATES------------------------------------------------------------->>>>
		
		if($week==null) {
			//echo "entered 1 with week = $week and year = $year";exit;
			$dateObject = new DateTime('NOW');
			$dateObject->setTimeZone(new DateTimeZone("America/Costa_Rica"));
			$week = $dateObject->format('W');
			$year = $dateObject->format('Y');		
			$week_start = new DateTime();
			$week_start->setTimeZone(new DateTimeZone("America/Costa_Rica"));
			$week_start->setISODate($year,$week);
		} else {
			//echo "entered 2 with week = $week and year = $year";exit;
			$week_start = new DateTime();
			$week_start->setTimeZone(new DateTimeZone("America/Costa_Rica"));
			$week_start->setISODate($year,$week);		
		}
		
		//creating an array with dayOfWeek => date entries in name format
		$daysArray = array();
		$daysArray[$week_start->format('l jS')] = $week_start->format('Y-m-d');
		$daysArray[date('l jS', strToTime('next Tuesday '.$week_start->format('Y-m-d')))] = date('Y-m-d', strToTime('next Tuesday '.$week_start->format('Y-m-d')));
		$daysArray[date('l jS', strToTime('next Wednesday '.$week_start->format('Y-m-d')))] = date('Y-m-d', strToTime('next Wednesday '.$week_start->format('Y-m-d')));
		$daysArray[date('l jS', strToTime('next Thursday '.$week_start->format('Y-m-d')))] = date('Y-m-d',  strToTime('next Thursday '.$week_start->format('Y-m-d')));
		$daysArray[date('l jS', strToTime('next Friday '.$week_start->format('Y-m-d')))] = date('Y-m-d',  strToTime('next Friday '.$week_start->format('Y-m-d')));
		$daysArray[date('l jS', strToTime('next Saturday '.$week_start->format('Y-m-d')))] = date('Y-m-d',  strToTime('next Saturday '.$week_start->format('Y-m-d')));
		$daysArray[date('l jS', strToTime('next Sunday '.$week_start->format('Y-m-d')))] = date('Y-m-d',  strToTime('next Sunday '.$week_start->format('Y-m-d')));		
		
		//creating an array with dayOfWeek => date entries in date format
		/*$daysArray = array();
		$daysArray[$week_start->format('l jS')] = $week_start->format('Y-m-d');
		$daysArray[date('l jS', strToTime('next Tuesday '.$week_start->format('Y-m-d')))] = date('Y-m-d', strToTime('next Tuesday '.$week_start->format('Y-m-d')));
		$daysArray[date('l jS', strToTime('next Wednesday '.$week_start->format('Y-m-d')))] = date('Y-m-d', strToTime('next Wednesday '.$week_start->format('Y-m-d')));
		$daysArray[date('l jS', strToTime('next Thursday '.$week_start->format('Y-m-d')))] = date('Y-m-d',  strToTime('next Thursday '.$week_start->format('Y-m-d')));
		$daysArray[date('l jS', strToTime('next Friday '.$week_start->format('Y-m-d')))] = date('Y-m-d',  strToTime('next Friday '.$week_start->format('Y-m-d')));
		$daysArray[date('l jS', strToTime('next Saturday '.$week_start->format('Y-m-d')))] = date('Y-m-d',  strToTime('next Saturday '.$week_start->format('Y-m-d')));
		$daysArray[date('l jS', strToTime('next Sunday '.$week_start->format('Y-m-d')))] = date('Y-m-d',  strToTime('next Sunday '.$week_start->format('Y-m-d'))); */
		
		//print_r($_GET);
		
		if(isset($_GET['isAjaxRequest'])) {
				$this->renderPartial('_FteReporting_content',
									  array(
											'week'=>$week,
											'year'=>$year,
											'days'=>$daysArray
											),
									false,
									true
							);			
		} else {
		    //echo "else way";exit;
			$this->render('FteReporting',
						  array(
								'week'=>$week,
								'year'=>$year,
								'days'=>$daysArray,
						));		
		}					
							
	}	
	
}
